﻿/*Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 
4  See LICENSE in the project root for license information */

var dialog;
var dialogW = 35;
var dialogH = 55;
function eventHandler(arg) {
    //Required, call event.completed to let the platform know you are done processing.
    clickEvent.completed();
    // In addition to general system errors, there are 2 specific errors 
    // and one event that you can handle individually.
    switch (arg.error) {
        case 12002:
            console.log("Cannot load URL, no such page or bad URL syntax.");
            break;
        case 12003:
            console.log("HTTPS is required.");
            break;
        case 12006:
            // The dialog was closed, typically because the user the pressed X button.
            console.log("Dialog closed by user");
            break;
        default:
            console.log("Undefined error in dialog window");
            break;
    }
}

/**
 * 下载文件
 * @param {any} event
 */
function download(event) {
    clickEvent = event;

 
    $.getJSON(kURL_ExcelBase64).then(function (json) {
        if (json.code == 200) {
            var docxString = json.data;
            open(docxString);
        } else {
            throw json.msg;
        }
    }).catch(function (jqXHR, textStatus, errorThrown) {

    }); 
}
 
function open(base64) {
    clickEvent.completed();
 
    Excel.run(function (context) {
        var document = context.application.createWorkbook(base64);
        document.open();

        return context.sync();
    }).catch(function (error) {
        console.log(error);
    });

}

/**
 * 提取数据
 * @param {any} event
 */
function getData(event) {
    clickEvent = event;

    showFillDialog();
}

/**
 * 提取数据向导页面
 */
function showFillDialog() {
    //IMPORTANT: IFrame mode only works in Online (Web) clients. Desktop clients (Windows, IOS, Mac) always display as a pop-up inside of Office apps. 
    var url = server + "/pages/exceldialog.html";
    Office.context.ui.displayDialogAsync(url,
        { height: dialogH, width: dialogW, displayInIframe: true }, getDataBack);
    
   //request("603306", 5, 12, 5, 1000000);
}

/**
 * 提取数据回调处理
 */
function getDataBack(result) {
    if (result.status == Office.AsyncResultStatus.Failed) {
        return;
    }

    dialog = result.value;

    /*Messages are sent by developers programatically from the dialog using office.context.ui.messageParent(...)*/
    dialog.addEventHandler(Office.EventType.DialogMessageReceived, getDataHandler);

    /*Events are sent by the platform in response to user actions or errors. For example, the dialog is closed via the 'x' button*/
    dialog.addEventHandler(Office.EventType.DialogEventReceived, eventHandler);
}

/**
 * 提取数据填充处理
 */
function getDataHandler(arg) {
    //TODO dialog时开启
     dialog.close();
      var json = JSON.parse(arg.message);

     //Test
     //var json = arg;

     var input = json.params;
     var datas = json.datas;
    Excel.run(function (context) {
        return context.sync()
            .then(function () {
                fillSheetAnnual(context, input, datas);
            })
            .then(context.sync)
            .then(function () {
                fillSheetCoreAssumption(context, input, datas);
            })
            .then(context.sync)
            .then(function () {

            })
            .then(context.sync)
            .then(function () {

            }).then(context.sync)
            .then(function () {

            }).then(context.sync)
            .then(function () {

            })
            .then(context.sync)
            .then(function () {

            })
            .then(context.sync)
            .then(function () {

            })
            .then(context.sync)
            .then(function () {
                clickEvent.completed();
            }).catch(function (e) {
                clickEvent.completed();
                console.log(e);
            });
    }).catch(function (e) {
        clickEvent.completed();
        console.log(e);
    });
}
 
function request(code, year, quarter, forceastYear, unit) {
     

    var params = JSON.parse("{}");
    params.year = year;
    params.quarter = quarter;
    params.forceastYear = forceastYear;
    params.unit = unit;

    //1.目录sheet
    var categoryUrl = kURL_Category + "?code=" + code + "&unit=" + unit;
    //2.年报sheet
    var annualUrl = kURL_Annual + "?code=" + code + "&unit=" + unit + "&nums=" + year;
    //3.季报sheet
    var quarterUrl = kURL_Quarter + "?code=" + code + "&unit=" + unit + "&nums=" + quarter;
    //4.单季报sheet
    var singleQuarterUrl = kURL_SingleQuarter + "?code=" + code + "&unit=" + unit + "&nums=" + quarter;
    //5.主营业务构成sheet
    var mainrevenuedetailUrl = kURL_Mainrevenuedetail + "?code=" + code + "&unit=" + unit + "&nums=" + year;

    var category;
    var annual;
    var quarter;
    var singleQuarter;
    var mainrevenuedetail;

    $.getJSON(categoryUrl).then(function (json) {
        if (json.code == 200) {
            category = json.data;
            return $.getJSON(annualUrl);
        } else {
            throw json.msg;
        }
    }).then(function (json) {
        if (json.code == 200) {
            annual = json.data;
            return $.getJSON(quarterUrl);
        } else {
            throw json.msg;
        }
    }).then(function (json) {
        if (json.code == 200) {
            quarter = json.data;
            return $.getJSON(singleQuarterUrl);
        } else {
            throw json.msg;
        }
    }).then(function (json) {
        if (json.code == 200) {
            singleQuarter = json.data;
            return $.getJSON(mainrevenuedetailUrl);
        } else {
            throw json.msg;
        }
    }).then(function (json) {
        if (json.code == 200) {
            mainrevenuedetail = json.data;
            return null;
        } else {
            throw json.msg;
        }
    }).then(function (j) {
        var datas = JSON.parse("{}");
        datas.category = category;
        datas.annual = annual;
        datas.quarter = quarter;
        datas.singleQuarter = singleQuarter;
        datas.mainrevenuedetail = mainrevenuedetail;

        var result = JSON.parse("{}");
        result.params = params;
        result.datas = datas;

        getDataHandler(result);

    }).catch(function (jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
        removeLoading('stock');
        if (typeof (jqXHR) == "string") {
            showMessage(jqXHR);
        } else {
            showMessage("网络连接失败，请检查网络");
        }
    });
}
 